package com.songcan.oauth.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.songcan.common.contans.CoreLoginSqlContants;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Slf4j
@NoArgsConstructor
public class WeChatLoginUtil {

    private String wxPublicAppId;
    private String wxPublicSecretKey;
    private RedisTemplate redisTemplate;
    public  WeChatLoginUtil ( String wxPublicAppId, String wxPublicSecretKeyu,RedisTemplate redisTemplate){
        this.wxPublicAppId = wxPublicAppId;
        this.wxPublicSecretKey = wxPublicSecretKeyu;
        this.redisTemplate = redisTemplate;
    }

    public WeixinLoginUserVo weixinLogin(String code) {
        /*
         * 获取微信用户登录授权、信息
         */
        WeixinLoginUserVo userInfo = null;
        try {
            WeixinAccessToken accessToken = (WeixinAccessToken) redisTemplate.opsForValue().get("WX_TOKEN");
            if(Objects.isNull(accessToken)){
                accessToken =  getAccessToken(code);
                redisTemplate.opsForValue().set("WX_TOKEN",accessToken,2, TimeUnit.HOURS);
            }

           userInfo= getUserInfo(accessToken);
            /*
             * 根据unionId 判断用户是否已绑定手机号，是-前端直接跳入首页，否-前端跳入手机绑定页面
             */
            checkMobileBind(userInfo);
        }catch (Exception e){
            log.error("调用微信授权异常:{}",e.getMessage());
            return null;
        }
        return userInfo;
    }


    /**
     * 获取accessToken
     */
    private WeixinAccessToken getAccessToken(String code) {
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        String url = String.format(accessTokenUrl, wxPublicAppId, wxPublicSecretKey, code);


        String jsonObject= HttpUtil.get(url, Charset.forName("UTF-8"));
        JSONObject jsonObject1 = JSONObject.parseObject(jsonObject);
        return JSONObject.toJavaObject(jsonObject1,WeixinAccessToken.class);
    }

    /**
     * 获取微信账户用户信息
     */
    private WeixinLoginUserVo getUserInfo(WeixinAccessToken weixinAccessToken) {
        String unionIdUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
        String url = String.format(unionIdUrl, weixinAccessToken.getAccess_token(), weixinAccessToken.getOpenid());
        String jsonObject= HttpUtil.get(url, Charset.forName("UTF-8"));
        JSONObject jsonObject1 = JSONObject.parseObject(jsonObject);
        return JSONObject.toJavaObject(jsonObject1,WeixinLoginUserVo.class);
    }



    /**
     * 检查此微信是否绑定了手机号
     */
    private void checkMobileBind(WeixinLoginUserVo userInfo) {
//        Map count = null;
//        try {
//            count = jdbcTemplate.queryForMap("select user_id from yfk_wx_user_info where union_id ='"+userInfo.getUnionid()+"'");
//        }catch (Exception e){
//            log.error(e.getMessage());
//        }
//        if(Objects.isNull(count)){
//            userInfo.setMobileBind(false);
//            jdbcTemplate.update(CoreLoginSqlContants.WECHAT_INSERT_SQL,new Object[]{IdWorker.getId(),
//                    userInfo.getOpenid(),userInfo.getNickname(),userInfo.getSex(),
//            userInfo.getProvince(),userInfo.getCity(),userInfo.getCountry(),userInfo.getHeadimgurl(),userInfo.getUnionid()});
//        }else{
//            Map user = null;
//            try{
//               user =  jdbcTemplate.queryForMap("select mobile,user_id from yfk_user where user_id = "+count.get("user_id").toString());
//            }catch (Exception e){
//                log.error(e.getMessage());
//            }
//            if(Objects.isNull(user)||Objects.isNull(user.get("mobile"))){
//                userInfo.setMobileBind(false);
//            }else{
//                userInfo.setMobileBind(true);
//            }
//
//        }


    }

    private void checkMobileBinds(WeixinLoginUserVo userInfo) {

//
//         userInfo = new WeixinLoginUserVo();
//         userInfo.setUnionid("o5tkut0o15oE6HvXdx4zL9Tlxaps");
//         userInfo.setOpenid("1233");;
//         userInfo.setCity("12323");
//        JSONObject count = null;
//        try {
//            count = jdbcTemplate.queryForObject(CoreLoginSqlContants.WECHAT_SELECT_BY_UNIONID_SQL, new Object[]{userInfo.getUnionid()}, JSONObject.class);
//        }catch (Exception e){
//            log.error(e.getMessage());
//        }
//        if(Objects.isNull(count)){
//            userInfo.setMobileBind(false);
//            jdbcTemplate.update(CoreLoginSqlContants.WECHAT_INSERT_SQL,new Object[]{IdWorker.getId(),userInfo.getOpenid(),null,null,null,userInfo.getUnionid(),
//                    userInfo.getNickname(),userInfo.getSex(),null,userInfo.getCountry(),userInfo.getProvince(),userInfo.getCity(),null, LocalDate.now(),null,null,0});
//        }else{
//            Map user = null;
//            try{
//                user = jdbcTemplate.queryForMap("select mobile,user_id from yfk_user where user_id = ?",new Object[]{count.get("user_id").toString()});
//            }catch (Exception e){
//                log.error(e.getMessage());
//            }
//            if(Objects.isNull(user)||Objects.isNull(user.get("mobile"))){
//                userInfo.setMobileBind(false);
//            }else{
//                userInfo.setMobileBind(true);
//            }
//
//        }


    }



}
